package com.mz.ieann.dokit.utils

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Environment
import android.os.Parcelable
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import com.alibaba.fastjson.JSON
import java.io.File
import java.io.FileOutputStream

/**
 * <p>------------------------------------------------------
 * <p> Copyright (C) 2021 zhangmz, All rights reserved.
 * <p> If there is technical discussion, you can contact zhangmz90@foxmail.com
 * <p>------------------------------------------------------
 * <p> 写文件，6.0以上只申请了Manifest.permission.WRITE_EXTERNAL_STORAGE权限
 * <p> 部分data目录下好像不是WRITE_EXTERNAL_STORAGE权限，还要得申请权限的结果进行处理
 *
 * @author Created by zhangmz
 * @date on 2022/5/9
 */
object FileWrite {

    /**
     * 申请文件读权限code
     */
    const val PERMISSION_RESULT_CODE: Int = 0X1001

    @JvmStatic
    fun <T: Parcelable> writeCards(name: String, bean: T, append: Boolean? = true, con: FragmentActivity? = null) {
        writeCards(name, JSON.toJSONString(bean), append, con)
    }

    @JvmStatic
    fun writeCards(name: String, content: String, append: Boolean? = true, con: FragmentActivity? = null) {
        if (Environment.getExternalStorageState() != Environment.MEDIA_MOUNTED) {
            Log.e("file", "external memory card does not exist")
            return
        }
        writeCards(Environment.getExternalStorageDirectory().path, name, content, append, con)
    }

    @JvmStatic
    fun <T: Parcelable> writeCards(path: String, name: String, bean: T, append: Boolean? = true, con: FragmentActivity? = null) {
        writeCards(path, name, JSON.toJSONString(bean), append, con)
    }

    @JvmStatic
    fun writeCards(path: String, name: String, content: String, append: Boolean? = true, con: FragmentActivity? = null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            con?.let {
                Log.v("file", "file write permission checkSelfPermission:${ContextCompat.checkSelfPermission(con, Manifest.permission.WRITE_EXTERNAL_STORAGE)}")
                if (ContextCompat.checkSelfPermission(con, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED){
                    Log.v("file", "file write permission not granted")
                    ActivityCompat.requestPermissions(con, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), PERMISSION_RESULT_CODE)
                    return
                }
                write(path, name, content, append)
                return
            }?: Log.v("file", "context can not be null")
            return
        }
        write(path, name, content, append)
    }

    /**
     * 写文件到指定目录
     */
    private fun write(path: String, name: String, content: String, append: Boolean? = true){
        var fos: FileOutputStream? = null
        runCatching {
            val file = File(path, name)
            var newFile = true
            if (!file.exists() || !file.isFile){
                newFile = file.createNewFile()
            }
            if (!newFile){
                Log.e("file", "create new file fail")
                return@runCatching
            }
            fos = FileOutputStream(file, append == true)
            fos?.write(content.toByteArray())
            fos?.flush()
        }.onFailure {
            Log.e("file", "write file error:$it")
        }.getOrNull().run {
            Log.v("file", "write file end")
            runCatching { fos?.close() }
        }
    }

}